<template>
  <el-form class="background" v-bind="$attrs" @submit.native.prevent>
    <el-form-item label="背景设置" class="shrink-process-label">
      <div class="shrink" @click="shrink('background')">
        <SvgIcon v-if="shrinkFlag.background" icon-class="ic_向上" />
        <SvgIcon v-else icon-class="ic_向下" />
      </div>
      <div class="line"></div>
      <div v-if="shrinkFlag.background" class="shrink-contain">
        <div class="row-item">
          <span>背景类型</span>
          <el-select
            popper-class="dark-select-popper"
            v-model="formData.backgroundType"
            @change="handler('backgroundType')"
          >
            <el-option
              v-for="list in backgroundTypes"
              :key="list.value"
              :label="list.label"
              :value="list.value"
            />
          </el-select>
        </div>
        <div class="row-item">
          <span>背景样式</span>
          <SelectBackground
            v-if="formData.backgroundType === 'SkyBox'"
            v-model="formData.skybox"
            :image-list="skyboxImgs"
            @change="(value) => change(value, 'SkyBox')"
          ></SelectBackground>

          <SelectBackground
            v-if="formData.backgroundType === 'bkgImg'"
            :model-value="formData.backgroundImage"
            :image-list="bkgImgs"
            :allow-upload="true"
            :allow-delete="true"
            @uploadBefore="uploadBefore"
            @deleteImage="deleteImage"
            @change="(value) => change(value, 'bkgImg')"
          ></SelectBackground>
        </div>
      </div>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { delActBkgImg, getActBkgImgList, getActSkyboxList, recCommonFile } from '@/api/scene';
import { retFilePath } from '@/utils';
import { ImageMIMETypes } from '@/views/enum/common';
import { SkyBoxImgType, SkyBoxMapping } from '@/views/enum/global-effect';
import { useRequest } from '@jl/common/composable';
import { messageUtil } from '@jl/element-plus/utils';
import { ElMessage } from 'element-plus';
import SelectBackground from './component/select-image.vue';

defineOptions({
  name: 'Background',
});

interface IProps {
  form: any;
}
const props = withDefaults(defineProps<IProps>(), {
  form: {},
});

const { run: bgImgListRun, data: bkgImgList } = useRequest<any, any>(getActBkgImgList, null);

const { run: skyboxListRun, data: skyboxList } = useRequest<any, any>(getActSkyboxList, null);

// 背景图
const bkgImgs = ref<any[]>([]);

const skyboxImgs = ref<any[]>([]);

const formData = ref<any>(null);
const backgroundTypes = [
  {
    label: '天空盒',
    value: 'SkyBox',
  },
  {
    label: '背景图',
    value: 'bkgImg',
  },
];

const shrinkFlag = reactive<any>({
  background: true,
});

formData.value = props.form;

const init = async () => {
  await searchBkg();
  await searchSkyBox();
};

const searchBkg = async () => {
  await bgImgListRun();
  bkgImgs.value = (bkgImgList.value || []).map((item: any) => ({
    ...item,
    url: retFilePath(item.url),
  }));
  // 默认值
  if (!formData.value.backgroundImage) {
    bkgImgs.value.length > 0 ? (formData.value.backgroundImage = bkgImgs.value[0]) : null;
  }
  if (formData.value.backgroundType === 'bkgImg') {
    if (formData.value.backgroundImage?.url) {
      cimInstance.api.updateBackgroundImage({
        showImage: true,
        dataSourceUrl: formData.value.backgroundImage.url,
      });
    }
  }
};

const searchSkyBox = async () => {
  await skyboxListRun();
  // 后端返回天空图数据处理
  skyboxImgs.value = (skyboxList.value || []).map((item: any) => {
    const imgList = item.subImgList.map((url: string) => retFilePath(url));
    const url = imgList.find((url: string) => SkyBoxImgType.every((ele) => !url.includes(ele)));
    const param: any = {};
    SkyBoxImgType.forEach((ele: string) => {
      const list = (imgList || []).filter((url: string) => url.includes(ele));
      const obj: any = {};
      for (const key in SkyBoxMapping) {
        obj[key] = list.find((url: string) => url.includes(SkyBoxMapping[key]));
      }
      param[ele] = obj;
    });
    return {
      name: item.skyboxName,
      url,
      param,
    };
  });
  if (!formData.value.skybox) {
    skyboxImgs.value.length > 0 ? (formData.value.skybox = skyboxImgs.value[0]) : null;
  }
  if (formData.value.backgroundType === 'SkyBox') {
    if (formData.value.skybox?.param) {
      formData.value.skybox.url =
        skyboxImgs.value.find((item: any) => item.name === formData.value.skybox.name)?.url || '';
      const param = toRaw(formData.value.skybox.param);
      const skybox = {
        enable: true,
        index: 1,
        name: 'skyName',
        type: 'skybox',
        dayPart: param,
      };
      console.log('-----skybox------', skybox);
      cimInstance.api.changeSkyBox(skybox);
    }
  }
};

init();

const cimInstance = window.cimInstance;

function shrink(str: string) {
  shrinkFlag[str] = !shrinkFlag[str];
}

function handler(fieldName: string) {
  if (fieldName === 'backgroundType') {
    // 背景图
    if (formData.value.backgroundType === 'bkgImg') {
      if (formData.value.backgroundImage?.url) {
        cimInstance.api.updateBackgroundImage({
          showImage: true,
          dataSourceUrl: formData.value.backgroundImage.url,
        });
      }
    }
    // 天空盒
    if (formData.value.backgroundType === 'SkyBox') {
      if (formData.value.skybox?.param) {
        const param = toRaw(formData.value.skybox.param);
        const skybox = {
          enable: true,
          index: 1,
          name: 'skyName',
          type: 'skybox',
          dayPart: param,
        };
        console.log('-----skybox------', skybox);
        cimInstance.api.changeSkyBox(skybox);
      }
    }
  }
}

async function uploadBefore(params: any) {
  const file: File = params.file;
  if (!ImageMIMETypes.includes(file.type)) {
    ElMessage.info('请上传图片');
    return;
  }
  const formData = new FormData();
  formData.set('resoType', '1');
  formData.set('resoName', params.fileName);
  formData.set('file', file);
  await recCommonFile({ data: formData });
  await searchBkg();
}

function deleteImage(image: any) {
  const originImg = bkgImgList.value.find((item: any) => image.name === item.name);
  if (originImg.name === formData.value.backgroundImage.name) {
    formData.value.backgroundImage = null;
  }
  delActBkgImg({ params: { resUrl: originImg.url } }).then(async (res: any) => {
    messageUtil.success('删除成功');
    await searchBkg();
    if (bkgImgs.value.length === 0) {
      formData.value.backgroundImage = null;
    }
  });
}

function change(value: any, type: string) {
  if (type === 'bkgImg') {
    formData.value.backgroundImage = value;
    cimInstance.api.updateBackgroundImage({
      showImage: true,
      dataSourceUrl: value.url,
    });
  }
  if (type === 'SkyBox') {
    const param = toRaw(value.param);
    const skybox = {
      enable: true,
      index: 1,
      name: 'skyName',
      type: 'skybox',
      dayPart: param,
    };
    console.log('-----skybox------', skybox);
    cimInstance.api.changeSkyBox(skybox);
  }
}
</script>

<style lang="less" scoped>
.background {
  :deep(.el-select) {
    margin-left: auto;
  }
  :deep(.select-background-style) {
    margin-left: auto;
  }

  :deep(.el-color-picker) {
    margin-left: 10px;

    .el-color-picker__trigger {
      width: 152px;
      padding: 3px 0;
      padding-left: 6px;
      border-radius: 4px;
      border: 1px solid rgba(69, 72, 81, 0.6);
      justify-content: flex-start;

      .el-color-picker__color {
        width: 24px;
        border-radius: 4px;
        border: 1px solid rgba(69, 72, 81, 0.6);
        border-radius: 4px;

        i.el-icon.el-color-picker__icon.is-icon-arrow-down {
          display: inline-block !important;
          position: absolute;
          right: -110px;
          font-size: 14px;
          color: #a8abb2;
        }
      }
    }
  }
}
</style>
